from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.middleware.sessions import SessionMiddleware
from fastapi.middleware.cors import CORSMiddleware

from app.database.database import engine, Base
from app.routers import auth, users, admin, menus, dashboard, monitor, files

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title="后台管理系统",
    description="基于FastAPI的后台管理系统",
    version="1.0.0"
)

# 添加中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(SessionMiddleware, secret_key="1234567890")

# 挂载静态文件
app.mount("/static", StaticFiles(directory="app/static"), name="static")

# 包含路由
app.include_router(auth.router, tags=["认证"])
app.include_router(admin.router, tags=["后台首页"])
app.include_router(users.router, prefix="/admin", tags=["用户管理"])
app.include_router(menus.router, prefix="/admin", tags=["菜单管理"])
app.include_router(dashboard.router, prefix="/admin", tags=["仪表盘"])
app.include_router(monitor.router, prefix="/admin", tags=["系统监控"])
app.include_router(files.router, prefix="/admin", tags=["文件管理"])

# API路由的前缀设置
# 这些路由已经包含在上面的路由中，由于我们在router内部添加了/api前缀

# 设置模板
templates = Jinja2Templates(directory="app/templates")

@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc):
    return templates.TemplateResponse("error.html", {"request": request, "message": "页面不存在"}, status_code=404)

@app.exception_handler(500)
async def server_error_exception_handler(request: Request, exc):
    return templates.TemplateResponse("error.html", {"request": request, "message": "服务器错误"}, status_code=500) 